package cn.jinjimi.app.main.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.widget.RelativeLayout;

import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.QuesCode;
import cn.jinjimi.app.common.DividerItemDecoration;
import cn.jinjimi.app.custom.ui.activity.CardListActivity;
import cn.jinjimi.app.custom.ui.activity.MakeCardActivity;
import cn.jinjimi.app.custom.ui.fragment.MakeCardFragment;
import cn.jinjimi.app.entity.CardItemData;
import cn.jinjimi.app.interfaces.CardFragmentView;
import cn.jinjimi.app.presenter.CardPresenter;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.main.adapter.recycler.CardRecAdapter;
import cn.jinjimi.app.main.extend.BaseNetControlFragment;
import cn.jinjimi.app.main.widget.XRecyclerView.XRecyclerView;

import java.util.List;

/**
 * Created by lforxeverc on 2016/10/18.
 */

public class CardFragment extends BaseNetControlFragment implements CardFragmentView, XRecyclerView.LoadingListener {
    private String title, nameTitle;
    private XRecyclerView recyclerView;
    private CardPresenter mPresenter;
    private CardRecAdapter mAdapter;
    private RelativeLayout emptyView;
    private LoadType mType;
    //加载场景贺卡或特定节日时需要用到
    private int mCardTypeId = -1;

    @Override
    public void onLoadFail(int page, String msg) {
        resetView(false);
        if (page == CardPresenter.DefaultPage && mAdapter.getItems().isEmpty()) {
            netLoadFaiEmpty();
        }
        ToastUtils.toastMessage(getActivity(), msg);
    }

    @Override
    public void onLoadSuccess(int page, List<CardItemData> data, boolean nomore) {
        resetView(page == CardPresenter.DefaultPage);
        if (page == CardPresenter.DefaultPage) {
            mAdapter.clearItems();
            netLoadSucc();
            if (mType == LoadType.HOLIDAY) {
                boolean bizViewShow = (data != null && !data.isEmpty());
                recyclerView.setVisibility(bizViewShow ? View.VISIBLE : View.GONE);
                emptyView.setVisibility(bizViewShow ? View.GONE : View.VISIBLE);
            }
        }
        mAdapter.addItems(data);
        initFooter(mAdapter.getItems(), nomore);

    }

    @Override
    public void onLoadCache(List<CardItemData> data) {
        if (data != null && !data.isEmpty()) {
            netLoadSucc();
            mAdapter.setItems(data);
            recyclerView.setNoMore(true);
        }
    }

    private void saveCache(List<CardItemData> data) {
        if (mPresenter != null)
            mPresenter.saveCache(data);
    }

    @Override
    public void onRefresh() {
        mPresenter.refresh();
    }

    @Override
    public void onLoadMore() {
        mPresenter.loadMoreData();
    }

    public enum LoadType {
        BIRTHDAY,//生日贺卡列表
        HOLIDAY,//所有节日贺卡列表
        SCENE_LIST,//所有场景贺卡列表
        HOLIDAY_WITH_ID,//某个ID节日贺卡列表
        SCENE_WITH_ID //某个ID情景贺卡列表
    }

    private void resetView(boolean refresh) {
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
        if (refresh)
            recyclerView.setRefreshTime(System.currentTimeMillis());
    }

    @Override
    protected int getBizLayoutResourceId() {
        return R.layout.fragment_card;
    }

    @Override
    protected void initialBiz() {
        nameTitle = getActivity().getIntent().getStringExtra(BundleKey.TITLE);
        final String mCustomId = getActivity().getIntent().getStringExtra("customId");
        final String mEnter = getActivity().getIntent().getStringExtra(BundleKey.PARAM_ENTER);
        emptyView = (RelativeLayout) findView().findViewById(R.id.empty_view);
        recyclerView = (XRecyclerView) findView().findViewById(R.id.rv_card);
        int pix20 = getActivity().getResources().getDimensionPixelSize(R.dimen.dp_20);
        int pix15 = getActivity().getResources().getDimensionPixelSize(R.dimen.dp_15);
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL_LIST)
                .setColorDivider(Color.TRANSPARENT).setDividerWidth(pix20));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST)
                .setColorDivider(Color.TRANSPARENT).setDividerWidth(mType == LoadType.SCENE_LIST ? pix15 : pix20));
        GridLayoutManager gm = new GridLayoutManager(getActivity(), mType == LoadType.SCENE_LIST ? 1 : 2);
        mAdapter = new CardRecAdapter(getActivity(), recyclerView, mType) {
            @Override
            public void onItemClick(CardItemData data) {
                if (mType == LoadType.BIRTHDAY ||
                        mType == LoadType.HOLIDAY ||
                        mType == LoadType.HOLIDAY_WITH_ID ||
                        mType == LoadType.SCENE_WITH_ID) {
                    if (AccountManager.getInstance().isLogin()) {
                        Intent intent = new Intent(getActivity(), MakeCardActivity.class);
                        intent.putExtra("type", data.itemData.getHolidayId());
                        intent.putExtra(BundleKey.TITLE, nameTitle);//客户名称
                        intent.putExtra("id", mCustomId);//客户id
                        intent.putExtra(BundleKey.PARAM_ENTER, mEnter);//来源

                        if (data != null && data.itemData != null) {
                            intent.putExtra("cardBean", data.itemData);
                            intent.putExtra("cardId", String.valueOf(data.itemData.getId()));
                        }

                        getActivity().startActivityForResult(intent, QuesCode.RequestCodeSendCard);
                    } else {
                        Router.doLogin(getActivity());
                    }
                } else if (mType == LoadType.SCENE_LIST) {
                    Intent ci = new Intent(getActivity(), CardListActivity.class);
                    ci.putExtra("title", nameTitle);
                    ci.putExtra("cardType", data.sceneData.sceneId);
                    ci.putExtra("loadType", CardListActivity.LOAD_SCENE_WITH_ID);
                    ci.putExtra("customId", mCustomId);
                    ci.putExtra("enter", MakeCardFragment.ENTER.HOLIDAY.getEnter());
                    getActivity().startActivity(ci);
                }
            }
        };
        recyclerView.setLayoutManager(gm);
        recyclerView.setLoadingListener(this);
        recyclerView.setAdapter(mAdapter);
        mPresenter = new CardPresenter(this, mType);
        if (mType == LoadType.SCENE_WITH_ID || mType == LoadType.HOLIDAY_WITH_ID) {
            mPresenter.setCardTypeId(mCardTypeId);
        }
        if (mType == LoadType.BIRTHDAY) {//生日类型手动设置cardId为0
            mPresenter.setCardTypeId(0);
        }
    }

    @Override
    protected void loadData() {
        mPresenter.loadCache();
        mPresenter.refresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        saveCache(mAdapter.getItems());
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setType(LoadType mType) {
        this.mType = mType;
    }

    public void setCardTypeId(int cardTypeId) {
        this.mCardTypeId = cardTypeId;
    }

    @Override
    public String getTitle() {
        return title;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == QuesCode.RequestCodeSendCard && resultCode == Activity.RESULT_OK) {
            getActivity().finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initFooter(final List<CardItemData> data, final boolean noMore) {
        if (mType == LoadType.SCENE_LIST) {
            recyclerView.setShowFooterWhenNoMore(data != null && !data.isEmpty());
            recyclerView.setNoMore(true);
        } else {
            recyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    int measuredHeight = recyclerView.getMeasuredHeight();
                    int headerRows = 0;
                    int itemRows = 0;
                    int curItemCounts = 0;
                    for (CardItemData item : data) {

                        if (item.type == CardItemData.Type.HEADER) {
                            if (curItemCounts != 0) {
                                if (curItemCounts % 2 == 0) {
                                    itemRows += curItemCounts / 2;
                                } else {
                                    itemRows += curItemCounts / 2 + 1;
                                }
                            }
                            curItemCounts = 0;
                            headerRows++;
                        } else if (item.type == CardItemData.Type.ITEM) {
                            curItemCounts++;
                        }
                    }
                    if (curItemCounts % 2 == 0) {
                        itemRows += curItemCounts / 2;
                    } else {
                        itemRows += curItemCounts / 2 + 1;
                    }
                    if (getActivity() == null) return;
                    int divideH = getActivity().getResources().getDimensionPixelSize(R.dimen.dp_20) * (itemRows + headerRows);
                    int itemsH = mAdapter.getItemViewHeight() * itemRows;
                    int headersH = mAdapter.getHeaderViewHeight() * headerRows;
                    int allHeight = itemsH + headersH + divideH;
                    if (allHeight > measuredHeight) {
                        recyclerView.setShowFooterWhenNoMore(true);
                    } else {
                        recyclerView.setShowFooterWhenNoMore(false);
                    }
                    recyclerView.setNoMore(noMore);
                }
            }, 100);
        }
    }
}
